package com.ruixinzheng.logicdemo;

public class TwoThread {
    private static volatile int count = 100;

    public static void main(String[] args) {
        new Thread(new Work(), "A").start();
        new Thread(new Work(), "B").start();
    }

    // 2个线程交替对count进行减1，并打印count
    static class Work implements Runnable {
        @Override
        public void run() {
            while (count > 0) {
                synchronized (Work.class) {
                    String name = Thread.currentThread().getName();
                    boolean isA = count % 2 == 0;
                    if (isA && "A".equals(name)) {
                        count--;
                        System.out.println(Thread.currentThread().getName() + " " + count);
                        Work.class.notify();
                    } else if (!isA && "B".equals(name)) {
                        count--;
                        System.out.println(Thread.currentThread().getName() + " " + count);
                        Work.class.notify();
                    } else {
                        try {
                            Work.class.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }
}
